{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Inference demo\n",
    "In this notebook, you can extract slide embeddings with out pretrained model TITAN."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import h5py\n",
    "import torch\n",
    "\n",
    "from transformers import AutoModel\n",
    "\n",
    "device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# load model\n",
    "model = AutoModel.from_pretrained('MahmoodLab/TITAN', trust_remote_code=True)\n",
    "model = model.to(device)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# load data\n",
    "from huggingface_hub import hf_hub_download\n",
    "demo_h5_path = hf_hub_download(\n",
    "    \"MahmoodLab/TITAN\", \n",
    "    filename=\"TCGA_demo_features/TCGA-PC-A5DK-01Z-00-DX1.C2D3BC09-411F-46CF-811B-FDBA7C2A295B.h5\",\n",
    ")\n",
    "file = h5py.File(demo_h5_path, 'r')\n",
    "features = torch.from_numpy(file['features'][:])\n",
    "coords = torch.from_numpy(file['coords'][:])\n",
    "patch_size_lv0 = file['coords'].attrs['patch_size_level0']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# extract slide embedding\n",
    "with torch.autocast(device_type='cuda', dtype=torch.bfloat16), torch.inference_mode():\n",
    "    features = features.to(device)\n",
    "    coords = coords.to(device)\n",
    "    slide_embedding = model.encode_slide_from_patch_features(features, coords, patch_size_lv0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "titan",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.20"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
